/*
 * ======================================================================
 * Button listeners
 * ======================================================================
 */

/* Pull down advanced search panel */
$('#advanced-search-button').click(function () {
    toggleAdvancedSearch();
});

/* Close the adv search panel */
$('.close-adv-search').click(function () {
    $('#advanced-search-button').removeClass('active, pressed');
    toggleAdvancedSearch();
});

/* Slide out the profile panel */
$('#profile-button').click(function () {
    $('#profile').toggleClass('stage-left');
    bringToFront('#profile');
});

/* Buttons look pressed when clicked */
$('.menu-btn').click(function () {
    $(this).toggleClass('pressed active ');
});

/* Return to dashboard */
$('.brand').click(function () {
    makeCurrent('#dashboard');
    switchTo('');
    $('#app-footer').removeClass('hide');
    $('#search-results-side, #seach-results-swipe .swipe-wrapper, #search-results-bullets ').empty();

});

/* Pull down the filter menu on search results */
$('.filter-btn').click(function () {
    $('#filter').toggleClass('up-stage on-screen');
});

$('#filter-close-button').click(function () {
    $('.filter-btn').removeClass('pressed active');
});

/* Slide out the messages panel */
$('#messages-button').click(function () {
    toggleMessages();
});

/* Small Screen only search button */
$('#search-button').click(function () {
    $('#top-buttons').toggleClass('stage-right');
    $('#advanced-search').addClass('up-stage');
    $('#advanced-search-button').removeClass('active pressed');

    $('#simple-search, #idox-logo, .brand').toggleClass('hide-mobile');
    $('#app-header .center').toggleClass('center');

});

/* clicking panels will bring them to the front */
$('.panel').click(function () {
    bringToFront('#' + $(this).attr('id'));
});


/*
 * ======================================================================
 * Messages Functions
 * ======================================================================
 */

/* Make messages window full width of screen */
$('.full-screen-button').click(function () {
    $('#messages-window').toggleClass('full-width');
    bringToFront('#messages-window');
});

/* Generate messages */
var msgCount = 1;
$('#message-reply-button').click(function () {

    //add a message, make it invisible
    $('.messages ').append('<article id="msg' + msgCount + '" class="message to opaque stage-animation">' +
        '<header class="box"><time class="pull-right">2012-08-10</time></header><p class="message-body">' +
        $('#message-reply-form .input').val()
        + '</p></article>');

    //clear the input field
    $('#message-reply-form .input').val('').css('height', '');

    //scroll to bottom
    $('#messages-wrapper').scrollTop($(document).height() * msgCount);

    //remove invisibilty from new message
    $('#msg' + msgCount).removeClass('opaque');
    msgCount++;

    return false;
});


/*
 * ======================================================================
 * Advanced Search
 * ======================================================================
 */

$('#simple-search form').submit(function () {
    doSearch();
});

$('#advanced-search-submit-button').click(function () {
    doSearch();
});

/* Set properties of loading modal */
$('#myModal').modal({
    backdrop:true
});

/* List and Grid View button listeners */
$('.list-view-btn').click(function () {
    makeCurrent('#search-results-page, .list-view');
    switchTo('search-results');

    $('.grid-view-btn').removeClass('pressed active');

});

$('.grid-view-btn').click(function () {
    makeCurrent('#search-results-page, .grid-view');
    switchTo('search-results');

    $('.list-view-btn').removeClass('pressed active');
});


$('.back-to-results-button').click(function () {
    makeCurrent('#search-results-page, .grid-view');
    switchTo('search-results');

    //empty the search results side bar on full-doc page
    $('#search-results-side').empty();
});

/*
 * ======================================================================
 * Full Document
 * ======================================================================
 */

/* Listener for search-result clicks */
$('.search-result, table.list-view tr').live('click', function () {

    switchTo('full-doc');
    makeCurrent('#full-document-page');

    //show loading screen
    $('#loadingModal').modal('show');

    //ajax load the document
    $.ajax({url:"../examples/document.html", success:function (result) {
        var src = $(result).filter('#full-doc-img').attr('src');
        $("#full-document-image").attr('src', src);

        $('#loadingModal').modal('hide');

    },

        error:function () {
            alert('Load Fail');
        }
    });

    // populate the search results sidebar
    $('.grid-view ul .search-page .thumbnails').each(function () {
        $('#search-results-side').append($(this).html());
    });
});


/*
 * =====================================================
 * Functions
 * =====================================================
 */


/* Change the mode of the app */
function switchTo(mode) {
    $('body').removeClass().addClass(mode);
}

/* Make a page of the app, active*/
function makeCurrent(page) {
    // when window gets resized, hidden swipeJS elements break when reshown
    dashboardSlider.setup(); // need to re setup

    $('.current').removeClass('current');
    $('' + page).addClass('current');
}

function toggleMessages() {
    $('#messages-window').toggleClass('stage-right on-screen');
    bringToFront('#messages-window');
}

function toggleAdvancedSearch() {
    bringToFront('#advanced-search');
    $('div#advanced-search').toggleClass('up-stage');

}

/* Bring requested element to the front of the screen.*/
function bringToFront(el) {
    $('.forefront').removeClass('forefront');
    $(el + '').addClass('forefront');
}

/* Mimick a search */
function doSearch() {
    //move into search results mode
    switchTo('search-results');
    makeCurrent('#search-results-page, #search-results-grid-view');

    for (var r = 0; r < 20; r++) {
        //create blank search pages
        $('#search-results-grid-view ul').append('<div class="search-page " id="page' + r + '"><div class="thumbnails"></div></div>');

        //create bullets
        $('#search-results-bullets').append('<em tabIndex="' + r + '">&#8226;</em>');

        //create the list view results
        $('table.list-view tr:last').after('<tr><td>Result 1</td><td>12-D0456-001</td><td>4</td><td>IFC</td><td>01/08/12</td></tr>');

    }

    $('#search-results-bullets em').click(function () {
        searchSlider.slide($(this).attr('tabIndex'), 500);
    });

    //make the first bullet active
    $('#search-results-bullets em').first().addClass('on');

    // fill the first two pages with results.
    populatePages(0, 1);

    //the first search page will be active on screen
    $('.search-page').first().addClass('active');


    /* Phones don't have swipeable results */
    if (Modernizr.mq('screen and (max-device-width: 480px)')) {

        $('#search-results-grid-view .swipe-wrapper').append('<button class="load-more-button">Load More</button>');

        $('.load-more-button').click(function () {
            var n = $('.filled').length;
            populatePages(n + 1, n + 1);
        });

    }

    /* Otherwise setup a slider */
    else {
        //initialise slider
        var searchSlider = new Swipe(document.getElementById('search-results-swipe'), {
            //on arrival at a new page
            callback:function (event, pos) {

                //active page is no longer active
                $('.search-page.active').removeClass('active');

                //make new page active
                $('#page' + pos).addClass('active');

                //if 15 pages of results
                if ($('.filled').length >= 15) {
                    $('.filled:lt(10)').removeClass('filled').find('.thumbnails').empty();
                    /*empty the first 10 pages*/

                }

                if (!$('#page' + (pos - 1)).length == 0 && !$('#page' + (pos - 1)).hasClass('filled')) {
                    populatePages((pos - 1), (pos));
                }

                else if (!$('#page' + (pos)).hasClass('filled')) {
                    populatePages((pos), (pos + 1));

                }
                //if the next page isn't filled with results
                else if (!$('#page' + (pos + 1)).length == 0 && !$('#page' + (pos + 1)).hasClass('filled')) {
                    $('#loadingModal').modal('show');

                    //load in search results to the next two pages using ajax
                    populatePages((pos + 1), (pos + 1));
                }


                //fix the bullets
                var i = bullets.length;
                while (i--)
                    bullets[i].className = '';
                bullets[pos].className = 'on';
            }
        }),
            bullets = document.getElementById('search-results-bullets').getElementsByTagName('em');

        //override the listener for main slider prev and next btns to work with the search results slider
        $('body.search-results .btn-prev').click(function () {
            searchSlider.prev();
        });

        $('body.search-results .btn-next').click(function () {
            searchSlider.next();
        });
    }
}

/* Populate search pages with results */
function populatePages(from, to) {

    $('#loadingModal').modal('show');

    //pull results using ajax
    $.ajax({url:"../examples/search.html", success:function (result) {

        for (var x = from; x <= to; x++)
            if (!$("#page" + x + ".search-page").hasClass('filled')) {  //if not already filled
                $("#page" + x + ".search-page").addClass('filled').html($(result).filter('#ajax-result').html());
            }

        $('#loadingModal').modal('hide');

    },
        error:function () {
            $('#loadingModal').modal('hide');
            alert('Loading Failed');
        }
    });
}
